import { useMenuStore } from '@/store'
import { MenuList } from '#/comm/menu'
import { Router, RouteRecordRaw } from 'vue-router'

export default function useMenu() {
  /**
   * 递归创建菜单路由
   * @param menuList 后台返回的菜单列表
   * @param parentId 上级ID
   * @returns
   */
  const createMenusRouter = (menuList: MenuList[], parentId: string): RouteRecordRaw[] => {
    const templateToCompoent = import.meta.glob('../views/**/*.vue')
    const itemArr: RouteRecordRaw[] = []
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < menuList.length; i++) {
      const node = menuList[i]
      if (node.parentId === parentId) {
        const newNode: RouteRecordRaw = {
          path: node.href,
          name: node.menuCode,
          component: node.component !== '' ? templateToCompoent[`../views${node.component}.vue`] : () => import('@/layout/page-layout.vue'),
          meta: {
            icon: node.menuIcon,
            id: node.id,
            title: node.menuName,
            isHidden: node.isShow === '1',
          },
          children: [],
        }
        newNode.children = createMenusRouter(menuList, node.id)
        itemArr.push(newNode)
      }
    }
    return itemArr
  }
  // 创建路由
  const createUserRouter = (router: Router) => {
    const menuStore = useMenuStore()
    const userRouter = createMenusRouter(menuStore.getMenuList, '0')
    menuStore.setRouterMenusList(userRouter)
    const list = router.options.routes
    userRouter.forEach((item: RouteRecordRaw) => list[0].children && list[0].children.push(item))
    list.map((r: RouteRecordRaw) => router.addRoute(r))
  }
  return { createUserRouter }
}
